<template>
  <div class="app-container">

    <!--    新增app-->
    <div style="margin: 10px 0; display: flex">
      <el-button type="primary" @click="showDialog('add')">新增商家</el-button>
    </div>

    <!--    表格数据-->
    <el-table
      v-loading="listLoading"
      :data="appData"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{(currentPage - 1) * pageSize + scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column label="商家名称">
        <template slot-scope="scope">
          {{ scope.row.shopName }}
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="所属学校" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.school }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="认证状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.authSuccess === '0' ? 'danger':'success'">{{ scope.row.authSuccess === '0' ?
            '未认证':'已认证' }}
          </el-tag>
        </template>
      </el-table-column>

      <!--操作列表-->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="edit(scope.row.id)" icon="el-icon-edit" circle></el-button>

          <el-popconfirm
            @onConfirm="setEnableState(scope.row.id, scope.row.authSuccess)"
            confirmButtonText='确定'
            cancelButtonText='取消'
            icon="el-icon-info"
            iconColor="orange"
            :title="scope.row.authSuccess === '1'? '确认取消认证？': '确认通过认证？'"
          >
            <el-button slot="reference" :type="scope.row.authSuccess === '0' ? 'success': 'warning'"
                       :icon="scope.row.authSuccess === '0' ? 'el-icon-check': 'el-icon-close'"
                       circle></el-button>
          </el-popconfirm>

          <el-popconfirm
            @onConfirm="del(scope.row.id)"
            confirmButtonText='确定'
            cancelButtonText='取消'
            icon="el-icon-info"
            iconColor="red"
            title="删除后不可恢复,是否继续？"
          >
            <el-button slot="reference" type="danger" icon="el-icon-delete"
                       circle></el-button>
          </el-popconfirm>

        </template>
      </el-table-column>

    </el-table>

    <!--    分页数据-->
    <div v-if="totalCount" style="margin: 20px 0; text-align: center">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="getAppList"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount">
      </el-pagination>
    </div>
    <!--弹出窗 新增 、 详情、 编辑-->
    <el-dialog

      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      width="70%"
      :before-close="handleClose">
      <el-form v-loading="dialogLoading" ref="appInfoForm" :rules="rules" :model="appInfoForm" label-width="80px">

        <div style="display: flex">
          <div style="width: 40%">
            <div>
              <el-upload
                class="avatar-uploader"
                action="api/file/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </div>
          <div>
            <el-form-item label="id" hidden prop="id">
              <el-input v-model="appInfoForm.id"/>
            </el-form-item>

            <el-form-item label="用户名" prop="username">
              <el-input v-model="appInfoForm.username"/>
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input v-model="appInfoForm.password"/>
            </el-form-item>

            <el-form-item label="店铺名称" prop="nickName">
              <el-input v-model="appInfoForm.shopName"/>
            </el-form-item>

            <el-form-item label="所属学校" prop="school">
              <el-input v-model="appInfoForm.school"/>
            </el-form-item>

            <el-form-item label="是否认证" prop="authSuccess">
              <el-switch v-model="appInfoForm.authSuccess"/>
            </el-form-item>


            <el-form-item label="联系人" prop="age">
              <el-input v-model="appInfoForm.name"/>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="appInfoForm.phone"/>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="appInfoForm.email"/>
            </el-form-item>

            <el-form-item label="地址" prop="shopAddress">
              <el-input v-model="appInfoForm.shopAddress"/>
            </el-form-item>

            <el-form-item label="店铺简介" prop="shopContent">
              <el-input type="textarea" v-model="appInfoForm.shopContent"/>
            </el-form-item>
          </div>
        </div>

      </el-form>


      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose()">取 消</el-button>
        <el-button type="primary" @click="saveAppInfo('appInfoForm')">确 定</el-button>
      </span>
    </el-dialog>

  </div>


</template>

<script>

  export default {
    name: 'Index',
    data() {
      return {
        imageUrl: '',
        appInfoForm: {},
        rules: {
          name: [
            {required: true, message: '请输入站点名称', trigger: 'blur'},
            {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
          ],
          url: [
            {required: true, message: '请输入站点地址', trigger: 'blur'},
            {min: 2, max: 120, message: '长度在 2 到 120 个字符', trigger: 'blur'}
          ],
        },
        dialogLoading: false,
        deleteDialogVisible: false,
        dialogType: '',
        appData: [],
        listLoading: true,
        dialogTitle: '提示',
        dialogVisible: false,
        totalCount: 0,
        currentPage: 1,
        pageSize: 10,
      }

    },
    created() {
      this.fetchData()
    },
    methods: {
      handleAvatarSuccess(res, file) {
        // console.log(res)
        this.imageUrl = res.data;
        this.appInfoForm.imgUrl = this.imageUrl
        // this.imageUrl = URL.createObjectURL(res.data);
      },
      beforeAvatarUpload(file) {
        console.log(file.type)
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG或PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },

      // 自定义格式化方法
      fetchData() {
        this.getAppList()
      },
      showDialog(type) {
        this.dialogType = type;
        if (type === 'add') {
          // 新增dialog
          this.dialogTitle = '新增商家';
          this.appInfoForm = {school: '默认学校'};
        } else if (type === 'update') {
          this.dialogTitle = '查看编辑';
        } else {
          this.$message.error('未知的操作类型');
        }
        this.dialogVisible = true
      },
      saveAppInfo(form) {
        if (!this.dialogType) {
          this.$message.error('未知的操作类型');
        } else {
          if (this.dialogType === 'add') {
            this.appInfoForm.id = ''
          }
          this.$refs[form].validate((valid) => {
            if (valid) {
              // 表单验证通过
              this.postApp(this.appInfoForm)
            }
          });
        }
      },
      postApp(pm) {
        this.dialogLoading = true;
        delete pm.updateTime;
        delete pm.createTime;
        delete pm.pageNo;
        delete pm.pageSize;
        pm.authSuccess = pm.authSuccess === true ? '1' : '0';
        this.$post('/shop/save', pm).then(res => {
          let dataTemp = res.data;
          if (dataTemp.success) {
            this.$message.success('保存成功');
            this.dialogVisible = false;
            this.getAppList();
            this.appInfoForm = {}
          } else {
            this.$message.error(dataTemp.msg);
          }
          this.dialogLoading = false
        })
      },
      del(id) {
        this.$post('/shop/delete', {
            id: id
          }
        ).then(res => {
          let dataTemp = res.data;
          if (dataTemp.success) {
            this.$message.success('操作成功');
            this.deleteDialogVisible = false;
            this.getAppList()
          } else {
            this.$message.error(dataTemp.msg);
          }
        })
      },
      setEnableState(id, state) {
        state = state === '0' ? '1' : '0';
        this.$post('/shop/save', {
            id: id,
            authSuccess: state
          }
        ).then(res => {
          let dataTemp = res.data;
          if (dataTemp.success) {
            this.$message.success('操作成功');
            this.deleteDialogVisible = false;
            this.getAppList()
          } else {
            this.$message.error(dataTemp.msg);
          }
        })
      },
      edit(id) {
        this.dialogLoading = true;
        this.showDialog('update');
        this.$get('/shop/query', {
          params: {
            id: id,
          }
        }).then(res => {
          let dataTemp = res.data;
          if (dataTemp.success) {
            this.appInfoForm = dataTemp.data;
            this.appInfoForm.authSuccess = dataTemp.data.authSuccess === '1';
            this.dialogLoading = false
            this.imageUrl = dataTemp.data.imgUrl
          } else {
            this.$message.error(dataTemp.msg);
          }

        })
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.getAppList(this.currentPage)
      },
      // 请求数据
      getAppList() {
        this.listLoading = true;
        this.$get('/shop/page', {
          params: {
            pageNo: this.currentPage,
            pageSize: this.pageSize,
          }
        }).then(res => {
          let dataTemp = res.data.data;
          this.appData = dataTemp.list;
          this.totalCount = dataTemp.total;
          this.listLoading = false
        })
      },
      handleClose() {
        this.dialogVisible = false
      }
    }
  }
</script>

<style>
  .el-button + .el-button {
    margin-left: 0px;
  }
</style>
